#include <windows.h>
#include "Application.h"
#include "Window.h"
#include "OpenGL.h"
#include "Mouse.h"
#include "Keyboard.h"
#include "Map.h"
#include "DynamicSphere.h"
#include "Engine.h"

BOOL WINAPI ConsoleHandler(DWORD CEvent)
{
    switch(CEvent)
    {
    case CTRL_C_EVENT:
        printf("CTRL+C received!");
        break;
    case CTRL_BREAK_EVENT:
        printf("CTRL+BREAK received!");
        break;
    case CTRL_CLOSE_EVENT:
		printf("Program being closed!");
		Application::SetWorking(false);
        break;
    case CTRL_LOGOFF_EVENT:
		printf("User is logging off!");
		Application::SetWorking(false);
        break;
    case CTRL_SHUTDOWN_EVENT:
		printf("Computer is shutting down!");
		Application::SetWorking(false);
        break;
    }
    return TRUE;
}

int main(void)
{
	if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleHandler,TRUE) == FALSE)
		printf("Unable to install handler!\n");

	Engine engine;	
	Application::SetWorking(true);	
	Application::SetInstance(NULL);	
			
	int width = GetSystemMetrics(SM_CXSCREEN);
	int height = GetSystemMetrics(SM_CYSCREEN);
	
	if(!Window::MainWindow().Create(L"AI", width, height))
	{
		MessageBox(NULL, L"Could not create window", L"Error", MB_OK);		
		return 1;
	}	

	if(!engine.Init(width, height))
	{
		MessageBox(NULL, L"Could not load map", L"Error", MB_OK);		
		return 2;
	}	
	
	MSG msg;	
	while(Application::Working())
	{
		if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message == WM_QUIT)				// Have We Received A Quit Message?		
				Application::SetWorking(false);	
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}	
		}
		else
		{
			engine.Maintain();			
		}
	}	

	engine.Destroy();

	return 0;
}